package cn.harry.cabinet.server.routes

import cn.harry.cabinet.repository.HardwareDeviceRepository
import cn.harry.cabinet.server.dto.common.ApiResponse
import cn.harry.cabinet.server.dto.hardware.HardwareDeviceResponse
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.call
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import io.ktor.server.routing.route
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.InternalSerializationApi

/**
 * 硬件设备API路由
 * 定义硬件设备管理的RESTful API接口
 */
@OptIn(InternalSerializationApi::class)
fun Route.hardwareDeviceRoutes(hardwareDeviceRepository: HardwareDeviceRepository) {

    route("/api/hardware-devices") {

        // 获取所有硬件设备
        get {
            try {
                withContext(Dispatchers.IO) {
                    val devices = hardwareDeviceRepository.getAllDevicesList()
                    val deviceResponses = HardwareDeviceResponse.fromHardwareDeviceList(devices)

                    call.respond(
                        HttpStatusCode.OK,
                        ApiResponse.success(deviceResponses, "获取硬件设备列表成功")
                    )
                }
            } catch (e: Exception) {
                call.respondError("获取硬件设备列表失败", e)
            }
        }

        // 获取所有启用的硬件设备
        get("/enabled") {
            try {
                withContext(Dispatchers.IO) {
                    val devices = hardwareDeviceRepository.getEnabledDevicesList()
                    val deviceResponses = HardwareDeviceResponse.fromHardwareDeviceList(devices)

                    call.respond(
                        HttpStatusCode.OK,
                        ApiResponse.success(deviceResponses, "获取启用的硬件设备列表成功")
                    )
                }
            } catch (e: Exception) {
                call.respondError("获取启用的硬件设备列表失败", e)
            }
        }
    }
}

/**
 * 私有扩展函数：响应服务器错误
 */
@OptIn(InternalSerializationApi::class)
private suspend fun io.ktor.server.application.ApplicationCall.respondError(message: String, exception: Exception) {
    println("$message: ${exception.javaClass.simpleName} - ${exception.message}")
    exception.printStackTrace()
    
    respond(
        HttpStatusCode.InternalServerError,
        ApiResponse.errorResponse(500, "$message: ${exception.message}")
    )
}
